package com.me.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name="AsyncServlet", urlPatterns ="/asyn", asyncSupported=true)
public class AsyncServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		final PrintWriter writer = resp.getWriter();
		writer.println("");
		writer.flush();
		
		final AsyncContext asyncContext = req.startAsync();
		
		System.out.println(asyncContext);
		asyncContext.setTimeout(10 * 1000);
		
		asyncContext.addListener(new AsyncListener(){
			public void onComplete(AsyncEvent event) throws IOException {
				// TODO Auto-generated method stub
				System.out.println("onComplete");  
			}
			public void onTimeout(AsyncEvent event) throws IOException {
				// TODO Auto-generated method stub
				System.out.println("onTimeout");  
			}
			public void onError(AsyncEvent event) throws IOException {
				// TODO Auto-generated method stub
				System.out.println("onError");  
			}
			public void onStartAsync(AsyncEvent event) throws IOException {
				// TODO Auto-generated method stub
				System.out.println("onStartAsync");  
			}
		});
		
		
		asyncContext.start(new Runnable(){
			public void run() {
				// TODO Auto-generated method stub
				try {
					//Thread.sleep(5*1000L);
					for(int i=0 ;i < 100; i++){
						writer.print("i = " + i); 
					}
					writer.println("Task finished");  
	                writer.flush();  
	                //异步调用完成，如果异步调用完成后不调用complete()方法的话，异步调用的结果需要等到设置的超时  
	                //时间过了之后才能返回到客户端。  
	                asyncContext.complete(); 
	                asyncContext.dispatch("/WEB-INF/jsp/template/1.jsp");
	                
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}  
			}
		});
		
		writer.println("go on other");  
	    writer.flush();
	    
	    
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(req, resp);
	}
	
	
	
	

}
